package com.veo.filter;


import com.veo.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;

/*@WebFilter(urlPatterns = "/*",initParams = {@WebInitParam(name = "exceptUrl",value = "/login&/login.jsp")})*/
public class LoginFilter implements Filter {
    private String exceptUrl="/login.jsp&/show.jsp&/getAllBooks&/codeImage&/login.action&/loginOut";
    private String[] exceptUrls;

    @Override
    public void init(FilterConfig config) throws ServletException {
        exceptUrls=exceptUrl.split("&");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request= (HttpServletRequest) req;
        //请求是登录或注册页面或登录控制器则不过滤（直接放行）
        HttpServletResponse response= (HttpServletResponse) resp;
        String url=request.getServletPath();
        if (Arrays.asList(exceptUrls).contains(url)||url.contains(".css")||url.contains("/bootstrap")||url.contains("/fonts")){
            chain.doFilter(req, resp);
            return;
        }
        //其他页面则进行验证是否登录
        HttpSession session = request.getSession();
        Object user = session.getAttribute("loginUser");
        if (user==null){
            request.setAttribute("msg","你尚未登录，请登录！");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }else {
            chain.doFilter(req, resp);
        }

    }

    @Override
    public void destroy() {
    }



}
